package com.proton.carepatchtemp.utils.net;

import android.os.SystemClock;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.constant.Settings;
import com.proton.carepatchtemp.database.Bean.ServerRequestXMPP;
import com.proton.carepatchtemp.database.RealData;
import com.proton.carepatchtemp.database.TestManager;
import com.proton.carepatchtemp.database.XmppMsg;
import com.proton.carepatchtemp.utils.JSONUtils;
import com.proton.carepatchtemp.utils.NetUtils;
import com.proton.carepatchtemp.utils.ThreadUtils;
import com.proton.carepatchtemp.utils.XmppUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;

/**
 * Created by MoonlightSW on 2017/1/5.
 */

public class XMPPCenter {

    public static final Queue<XmppMsg> msgQueue = new ConcurrentLinkedQueue<>();//数据队列

    private static void sendXmppMsg(final long uid, final org.jivesoftware.smack.packet.Message xmppMsg) {
        if ("0".equalsIgnoreCase(uid + "")) {
            return;
        }
        LogUtils.d(xmppMsg.getBody());
        String uidStr = String.valueOf(uid);
        Chat chat = VCare.get().getChatroom(uidStr);
        if (chat != null) {
            try {
                chat.send(xmppMsg);
            } catch (SmackException.NotConnectedException | InterruptedException e) {
                LogUtils.e(e);
            } finally {
            }
        }
    }

    public static void sendMsg(final String msg, final long uid) {
        ThreadUtils.postMsg(() -> {
            Message message = new Message();
            message.setBody(msg);
            try {
                message.setFrom(JidCreate.bareFrom(VCare.get().getXmppAct()));
            } catch (XmppStringprepException e) {
                LogUtils.e(e);
            }
            sendXmppMsg(uid, message);
        });
    }

    public static void sendMsg(final XmppMsg msg, final long uid) {
        if (msg == null) return;
        ThreadUtils.postMsg(() -> {
            Message message = new Message();
            message.setBody(msg.toString());
            try {
                message.setFrom(JidCreate.bareFrom(VCare.get().getXmppAct()));
            } catch (XmppStringprepException e) {
                LogUtils.e(e);
            }
            sendXmppMsg(uid, message);
        });
    }

    public static void sendMsgCustom(final XmppMsg msg, final long uid) {
        if (msg == null) return;
        Message message = new Message();
        message.setBody(msg.toString());
        message.setFrom(VCare.get().getXmppAct());
        sendXmppMsg(uid, message);
    }

    public static void loginChat() {
        final ExecutorService imagePool = VCare.get().getCachePool();
        imagePool.execute(() -> {
            boolean flag = true;
            if (NetUtils.hasNet()) {
                while (flag) {
                    try {
                        XMPPTCPConnection conn = VCare.get().getXmppConnection();
                        if (conn != null) {
                            if (!conn.isConnected()) {

                                try {
                                    conn.connect();
                                } catch (Throwable e) {
                                    LogUtils.e(e);
                                    SystemClock.sleep(2000);
                                    break;
                                }
                                try {
                                    conn.addConnectionListener(VCare.get().getTaxiListener());
                                    conn.login("user" + VCare.get().getUid(), "123456");
                                    LogUtils.e("xmpp登录成功,user = " + VCare.get().getUid());
                                } catch (Exception e) {
                                    LogUtils.e("xmpp登录失败");
                                    break;
                                }
                                flag = false;
                            } else {
                                flag = false;
                                LogUtils.e("xmpp已经登录");
                            }
                        } else {
                            SystemClock.sleep(2000);
                        }

                    } catch (IllegalThreadStateException e) {
                        LogUtils.e(e);
                    }
                }
            }
        });
    }

    public static void onMessage() {
        XMPPTCPConnection conn = VCare.get().getXmppConnection();
        if (conn != null) {
            ChatManager manager = ChatManager.getInstanceFor(conn);
            manager.addIncomingListener((from, message, chat) -> {
                LogUtils.d("From : " + message.getFrom() + "  Content: " + message.getBody());
                if (message.getType() == Message.Type.error) {
                    LogUtils.e(message);
                    return;
                }

                String msg = message.getBody();
                try {
                    msg = msg.replace("\\n", "");
                } catch (Throwable e) {
                    LogUtils.e(e);
                }

                if (msg.contains("XMPPMessageType")) {
                    Gson gson = new Gson();
                    ServerRequestXMPP serverRequestXMPP = JSONUtils.getObj(msg, ServerRequestXMPP.class);
                    for (RealData r :
                            TestManager.container.values()) {
                        if (r.getProfileID() == serverRequestXMPP.getProfileId() && r.isTesting) {
                            serverRequestXMPP.setRealTemp(r.realTemp + "");
                            serverRequestXMPP.setMaxTemp(r.warningHigh + "");
                            serverRequestXMPP.setMinTemp(r.warningLow + "");
                            sendMsg(gson.toJson(serverRequestXMPP), Long.parseLong(XmppUtils.getUidFromMsg(message)));
                            return;
                        }
                    }
                    sendMsg(gson.toJson(serverRequestXMPP), Long.parseLong(XmppUtils.getUidFromMsg(message)));
                    return;
                }

                final String uid = XmppUtils.getUidFromMsg(message);
                if (!uid.equalsIgnoreCase(VCare.get().getUid() + "")) {
                    if (!Settings.enableShare || !VCare.get().imConnected) {
                        return;
                    }
                    final String finalMsg = msg;
                    XmppMsg xmppMsg = JSONUtils.getObj(finalMsg, XmppMsg.class);
                    //判断是否离线消息，两分钟外判断为离线消息
                    if (null != xmppMsg && System.currentTimeMillis() - xmppMsg.getNow() <= 2 * 60 * 1000) {
                        LogUtils.i(xmppMsg);
                        EventBus.getDefault().post(new MainEvent(xmppMsg.getReportId() + "", Codes.XMPP_MSG_DATA, Extras.RET_S, XmppUtils.getUidFromMsg(message), xmppMsg));
                    }
                } else {

                }

            });
//            manager.addChatListener((chat, arg1) -> {
//
//                chat.addMessageListener((chat1, message) -> {
//                    LogUtils.e(message.getBody());
//                    LogUtils.e(message.toString());
//                    if (message.getType() == Message.Type.error) {
//                        return;
//                    }
////                    LogUtils.i("123456789");
//                    LogUtils.i(message.getFrom());
//                    LogUtils.i(message.getBody());
//                    String msg = message.getBody();
//                    try {
//                        msg = msg.replace("\\n", "");
//                    } catch (Throwable e) {
//                        LogUtils.e(e);
//                    }
//
//                    if (msg.contains("XMPPMessageType")) {
//                        Gson gson = new Gson();
//                        ServerRequestXMPP serverRequestXMPP = JSONUtils.getObj(msg, ServerRequestXMPP.class);
//                        for (RealData r :
//                                TestManager.container.values()) {
//                            if (r.getProfileID() == serverRequestXMPP.getProfileId() && r.isTesting) {
//                                serverRequestXMPP.setRealTemp(r.realTemp + "");
//                                serverRequestXMPP.setMaxTemp(r.warningHigh + "");
//                                serverRequestXMPP.setMinTemp(r.warningLow + "");
//                                sendMsg(gson.toJson(serverRequestXMPP), Long.parseLong(XmppUtils.getUidFromMsg(message)));
//                                return;
//                            }
//                        }
//                        sendMsg(gson.toJson(serverRequestXMPP), Long.parseLong(XmppUtils.getUidFromMsg(message)));
//                        return;
//                    }
//                    final String uid = XmppUtils.getUidFromMsg(message);
//                    if (!uid.equalsIgnoreCase(VCare.get().getUid() + "")) {
//                        if (!Settings.enableShare || !VCare.get().imConnected) {
//                            return;
//                        }
//                        final String finalMsg = msg;
////                        ThreadUtils.postMsg(() -> {
//                        XmppMsg xmppMsg = JSONUtils.getObj(finalMsg, XmppMsg.class);
//
//                        //判断是否离线消息，两分钟外判断为离线消息
//                        if (null != xmppMsg && System.currentTimeMillis() - xmppMsg.getNow() <= 2 * 60 * 1000) {
//                            LogUtils.i(xmppMsg);
//                            EventBus.getDefault().post(new MainEvent(xmppMsg.getReportId() + "", Codes.XMPP_MSG_DATA, Extras.RET_S, XmppUtils.getUidFromMsg(message), xmppMsg));
//                        }
////                        });
//                    } else {
//
//                    }
//                });
//            });
        }
    }
}
